package com.work.content;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.example.logindesign.R;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class WorkEditActivity extends Activity{
	private static final String NAMESPACE = "http://tempuri.org/";
	private static final String ENDPOINT = "http://192.168.1.198:1536/CommunitySystemsicWsWF.asmx";

	private String methodName;
	private String soapAction;
	private String unitcode;
	private String username;
	private String userid;
	// 编辑添加标识
	private String operateFlag = "Add";
	// 保存按钮
	private Button btnSave;
	// 返回 个按钮
	private ImageButton btnBack;

	// textview控件 2个
	private EditText editTextTime;
	private EditText editTextMsg;

	private String shequ="";
	private String name="";
	
	// EditText的值
	private String editTextTimeValue = "";
	private String editTextMsgValue = "";


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_work_edit);
		// sharedpreference中取得相应值
		getValueFromSharedPreferences();
		// 绑定EditText等控件
		initEditTextEtc();

		// 保存、返回按钮绑定及监听
		initButton();
	}

	/**
	 * sharedpreference中取得相应值
	 */
	private void getValueFromSharedPreferences() {
		// TODO Auto-generated method stub
		SharedPreferences sharedPreferences = getSharedPreferences("UserInfo",
				Activity.MODE_PRIVATE);
		username = sharedPreferences.getString("username", "");
		userid = sharedPreferences.getString("userid", "");
		unitcode = sharedPreferences.getString("unitcode", "");
	}

	/**
	 * 保存按钮绑定及监听
	 */
	private void initButton() {
		// TODO Auto-generated method stub
		btnBack = (ImageButton) findViewById(R.id.btn_event_edit_back);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 返回listview页面
				skipListViewActivity();
			}
		});
		btnSave = (Button) findViewById(R.id.btn_event_edit_save);
		btnSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				editTextTimeValue = editTextTime.getText().toString().trim();
				editTextMsgValue = editTextMsg.getText().toString().trim();

				// 提交数据
				new saveDataTask().execute();
			}
		});
	}

	private class saveDataTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String resultString = submitData();
			try {
				JSONArray jsonArray = new JSONArray(resultString);
				JSONObject jsonObject = jsonArray.optJSONObject(0);
				if (jsonObject.optString("Code").equals("1")) {
					return "success";
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "fail";
			}
			return "fail";
		}

		protected void onPostExecute(String finallyResultString) {
			if (finallyResultString.equals("success")) {
				Toast.makeText(WorkEditActivity.this, operateFlag + "成功",
						Toast.LENGTH_LONG).show();
				// 跳转到listview页面
				skipListViewActivity();
			} else {
				Toast.makeText(WorkEditActivity.this, operateFlag + "失败",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	/**
	 * 提交数据
	 * 
	 * @return
	 */
	private String submitData() {
		// TODO Auto-generated method stub
		String resultString = "";
		if (operateFlag.equals("Edit")) {
			methodName = "modify_SysWorkLog";
			soapAction = "http://tempuri.org/modify_SysWorkLog";
		} else {
			methodName = "add_SysWorkLog";
			soapAction = "http://tempuri.org/add_SysWorkLog";
		}
		SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
		// 当前提交时间 yyyy-MM-dd HH:mm:ss
		Date nowTime = new Date(System.currentTimeMillis());
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String curDate = sdFormatter.format(nowTime);

		// 用户名
		soapObject.addProperty("username", username);
		// 操作人员所属区域编码
		soapObject.addProperty("unitcode", unitcode);
		// 操作时间
		soapObject.addProperty("createtime", curDate);
		// 工作内容
		soapObject.addProperty("msg", editTextMsgValue);

		if (operateFlag.equals("Edit")) {
			// 操作人员id
			soapObject.addProperty("id", userid);
		}

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soapObject);
		Log.e("soapobject", soapObject.toString());
		envelope.dotNet = true;
		HttpTransportSE transportSE = new HttpTransportSE(ENDPOINT);
		try {
			transportSE.call(soapAction, envelope);
			if (envelope.getResponse() != null) {
				SoapObject object = (SoapObject) envelope.bodyIn;
				resultString = object.getProperty(0).toString();
				Log.e("webservice取得", resultString);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultString;
	}

	/**
	 * 设置EditText等控件，不能有耗时的操作
	 */
	private void initEditTextEtc() {
		// TODO Auto-generated method stub
		editTextTime = (EditText) findViewById(R.id.EditTextTime);
		editTextMsg = (EditText) findViewById(R.id.EditTextMsg);
		// setText 更新ui耗时操作放到了线程里
		new setEditTextEtcTask().execute();
	}

	/**
	 * 登记时间等控件初始化
	 */
	private class setEditTextEtcTask extends AsyncTask<Void, Void, String> {

		protected void onPreExecute() {
			// 设置EditText值
			setEditTextValue();
		}

		@Override
		protected String doInBackground(Void... params) {
			Intent getEditorAdd = getIntent();
			operateFlag = getEditorAdd.getStringExtra("operateFlag");
			if (operateFlag.equals("Edit")) {
				
				editTextTimeValue = getEditorAdd.getStringExtra("createtime");
				shequ = getEditorAdd.getStringExtra("username");
				name = getEditorAdd.getStringExtra("unitcode");
				editTextMsgValue = getEditorAdd.getStringExtra("msg");
				userid =getEditorAdd.getStringExtra("id");
			}
			return null;
		}

		protected void onPostExecute(String resultString) {
			// 设置EditText值
			setEditTextValue();
		}
	}

	/**
	 * 设置EditText的值
	 */
	private void setEditTextValue() {
		// TODO Auto-generated method stub
		editTextTime.setText(editTextTimeValue);
		editTextMsg.setText(editTextMsgValue);	
	}

	/**
	 * 跳转到listview页面
	 */
	private void skipListViewActivity() {
		Intent listviewIntent = new Intent();
		listviewIntent.setClass(WorkEditActivity.this,
				WorkListViewActivity.class);
		WorkEditActivity.this.startActivity(listviewIntent);
		WorkEditActivity.this.finish();
	}

	/**
	 * 重写keydown事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			skipListViewActivity();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
